package com.lagou.java;

import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.java.models.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;

@SpringBootApplication
@RestController
public class Application {

//    @Autowired(required = false)
//    private JdbcTemplate jdbcTemplate;

    static ConfigurableApplicationContext context = null;

    @GetMapping("/getId/{id}")
    public String getId(@PathVariable("id") String id) {
        JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);
        String sql="select id, name , age from tb_user_info where id=?";
        RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
        User user= jdbcTemplate.queryForObject(sql, rowMapper,1);
        System.out.println(user.toString());
        return user.toString();
    }

    // 测试数据库切换
    @RequestMapping("/updateConnection")
    public String updateConnection (String dataBase) {
        try {
            DruidDataSource dataSource = (DruidDataSource) context.getBean("dataSource");
            //数据源在启动时候已经初始化过，如果要切换数据库，需先执行restart,销毁之前的连接池，重新创建连接池
//            dataSource.restart();
//            dataSource.setUrl("jdbc:mysql:///" + dataBase + "?serverTimezone=UTC&useSSL=false&characterEncoding=utf8");
            ZkBoostrap zkBoostrap = new ZkBoostrap();
            ConfigInfo info = zkBoostrap.get();
            info.setDbName(dataBase);
            zkBoostrap.set(info);

        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return "数据库连接更新成功";
    }

    public static void main(String[] args) {
        new ZkBoostrap();
        context = SpringApplication.run(Application.class, args);
        ConfigInfo configInfo = context.getBean("node", ConfigInfo.class);
        new ZkBoostrap().create(configInfo);
    }
}
